package com.litchi.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author LitchiShell
 * @description:
 * @create 2022-04-17
 */
public class LitchiApplicationContext {

    private Class configClass;

    private static final String SINGLETON = "singleton";

    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    // 单例池
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();

    private ArrayList<BeanPostProcess> beanPostProcessList = new ArrayList<>();

    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);

        if (beanDefinition == null) {
            throw new NullPointerException();
        } else {
            String scope = beanDefinition.getScope();
            if (SINGLETON.equals(scope)) {
                Object bean = singletonObjects.get(beanName);
                if (bean == null) {
                    bean = createBean(beanName, beanDefinition);
                    singletonObjects.put(beanName, bean);
                }
                return bean;
            } else {
                return createBean(beanName, beanDefinition);
            }
        }
    }

    public LitchiApplicationContext(Class configClass) {
        this.configClass = configClass;

        // spring启动之后，扫描
        if (configClass.isAnnotationPresent(ComponentScan.class)) {

            ComponentScan configClassAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            // 扫描路径 com.litchi.service
            String path = configClassAnnotation.value();
            // com/litchi/service
            path = path.replace(".", "/");

            ClassLoader classLoader = LitchiApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);

            File file = new File(resource.getFile());

            if (file.isDirectory()) {
                File[] files = file.listFiles();

                for (File f : files) {
                    String fileAbsoluteName = f.getAbsolutePath();

                    if (fileAbsoluteName.endsWith(".class")) {

                        String className = fileAbsoluteName.substring(fileAbsoluteName.indexOf("com"), fileAbsoluteName.indexOf(".class"));

                        className = className.replace("/", ".");

                        Class<?> clazz = null;
                        try {
                            clazz = classLoader.loadClass(className);

                            if (clazz.isAnnotationPresent(Component.class)) {

                                if (BeanPostProcess.class.isAssignableFrom(clazz)) {
                                    BeanPostProcess instance = (BeanPostProcess) clazz.newInstance();
                                    beanPostProcessList.add(instance);
                                }

                                Component annotation = clazz.getAnnotation(Component.class);
                                String beanName = annotation.value();

                                if ("".equals(beanName)) {
                                    beanName = Introspector.decapitalize(clazz.getSimpleName());
                                }
                                // BeanDefinition
                                BeanDefinition beanDefinition = new BeanDefinition();
                                beanDefinition.setType(clazz);
                                if (clazz.isAnnotationPresent(Scope.class)) {
                                    Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
                                    beanDefinition.setScope(scopeAnnotation.value());
                                } else {
                                    beanDefinition.setScope(SINGLETON);
                                }

                                // 存储beanDefinition
                                beanDefinitionMap.put(beanName, beanDefinition);
                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        } catch (InstantiationException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        // 实例化单例bean
        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);

            if (SINGLETON.equals(beanDefinition.getScope())) {
                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }
        }
    }

    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getType();
        try {
            Object instance = clazz.getConstructor().newInstance();

            // 依赖注入
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    field.setAccessible(true);
                    field.set(instance, getBean(field.getName()));
                }
            }

            // beanName的Aware回调
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }
            // 初始化之前
            for (BeanPostProcess beanPostProcess : beanPostProcessList) {
                beanPostProcess.postProcessBeforeInitialization(beanName, instance);
            }
            // 初始化
            if (instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }

            // 初始化后 AOP BeanPostProcess
            for (BeanPostProcess beanPostProcess : beanPostProcessList) {
                instance = beanPostProcess.postProcessAfterInitialization(beanName, instance);
            }
            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }
}
